import type { SelectOptionItem } from "/@/types/antd";
import { useI18n } from "/@/locales/useI18n";

export function firstCharToUpper(str: string) {
  if (!str || typeof str != "string") return str;
  return str.replace(str[0], str[0].toUpperCase());
}

export function coverObj(
  originObj: { [key: string]: any },
  newObj: { [key: string]: any },
  cb?: (key: string, value: any) => any
) {
  for (const i in originObj) {
    const newValue = newObj[i];
    if (newValue !== undefined) {
      if (cb) {
        const result = cb(i, newValue);
        if (result !== undefined) {
          originObj[i] = result;
          continue;
        }
      }
      originObj[i] = newValue;
    }
  }
}

/**
 * 枚举类型数据转换为antd select options数据
 * @param enumData 枚举类型数据
 * @param localKey 对应locales中baseData中的key，若有值，则需要将label翻译
 * @returns antd select options数据
 */
export function enumToOptions(enumData: Record<string, any>, localKey?: string) {
  const result: SelectOptionItem[] = [];
  const { t } = useI18n();
  for (let key in enumData) {
    if (/^[\d]+$/.test(key)) continue;
    result.push({
      label: localKey ? t(`baseData.${localKey}.${key}`) : key,
      value: enumData[key],
    });
  }
  return result;
}

export function toOptions() {}

/**
 * 根据枚举类型数据获取指定value的item的label值
 * @param value antd select option的value值
 * @param enumData 枚举类型数据
 * @param localKey 对应locales中baseData中的key，若有值，则需要将label翻译
 * @returns {string | null} antd select label数据
 */
export function getLabelByValueFromEnum(value: string | number, enumData: Record<string, any>, localKey?: string) {
  const data = enumToOptions(enumData, localKey);
  const target = data.find((el) => el.value === value);
  return target ? target.label : null;
}

/**
 *
 * @param data  blob类型数据
 * @param fileName 导出文件名
 */
interface DowloadFileOptions {
  name?: string;
  contentType?: "application/vnd.ms-excel" | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
export function downloadFile(data: Blob, fileNameOrOptions?: string | DowloadFileOptions) {
  let options: DowloadFileOptions = {
    name: "",
    contentType: "application/vnd.ms-excel",
  };
  if (fileNameOrOptions) {
    if (typeof fileNameOrOptions == "string") {
      options.name = fileNameOrOptions;
    } else {
      Object.assign(options, fileNameOrOptions);
    }
  }
  let blob = new Blob([data], { type: options.contentType });
  let url = window.URL.createObjectURL(blob);
  const link = document.createElement("a"); // 创建a标签
  link.href = url;
  link.download = options.name ? options.name : `导出文件`; // 重命名文件
  link.click();
  URL.revokeObjectURL(url); // 释放内存
}

/**
 * 高德地图定位
 * @type {{}}
 */
export const location = {
  initMap(id) {
    let mapObj = new AMap.Map(id, {});
    let geolocation;
    mapObj.plugin(["AMap.Geolocation"], function () {
      geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //  是否使用高精度定位，默认:true
        timeout: 10000, //  超过10秒后停止定位，默认：无穷大
        maximumAge: 0, // 定位结果缓存0毫秒，默认：0
        convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        showButton: true, //  显示定位按钮，默认：true
        buttonPosition: "LB", // 定位按钮停靠位置，默认：'LB'，左下角
        buttonOffset: new AMap.Pixel(10, 20), //  定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showMarker: true, //  定位成功后在定位到的位置显示点标记，默认：true
        showCircle: true, //  定位成功后用圆圈表示定位精度范围，默认：true
        panToLocation: true, //  定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      });
      mapObj.addControl(geolocation);
      geolocation.getCurrentPosition();
    });
    return geolocation;
  },
};

export function isNullOrUndefOrEmpty(v) {
  return v === "" || v === undefined || v === null;
}

export function handleValue(value, subValue?) {
  if (isNullOrUndefOrEmpty(value)) {
    return "--";
  }
  return `${value}${isNullOrUndefOrEmpty(subValue) ? "" : `(${subValue})`}`;
}

// table 无数据占位符
export function customRender({ text }) {
  return text || "-";
}

export function isEmptyObj(val) {
  if (typeof val !== "object" || !val) return false;
  for (const i in val) {
    return false;
  }
  return true;
}

export function isObj(val) {
  return Object.prototype.toString.call(val) === "[object Object]";
}

export function deepMergeObj(targetObj, newObj) {
  for (let i in newObj) {
    const val = newObj[i];
    if (isObj(val)) {
      const targetVal = targetObj[i];
      if (isObj(targetVal)) {
        deepMergeObj(targetVal, val);
      } else {
        targetObj[i] = val;
      }
    } else {
      targetObj[i] = val;
    }
  }
}

/**
 * 将数值保留N位小数并返回，最后的0去掉
 * getFloatInteger(3.22222,2) => 3.22
 * getFloatInteger(3.2,2) => 3.2
 * getFloatInteger(3,2) => 3
 */
export function getFloatInteger(value: string | number, suf?: number) {
  value = Number(value);
  if (!value && value !== 0) {
    return "--";
  }
  let result = value.toFixed(suf || 2);
  let arr = result.split(".");
  if (parseInt(arr[1]) === 0) {
    return Number(arr[0]);
  } else {
    return Number(`${arr[0]}.${arr[1].replace(/[0]+$/, "")}`);
  }
}

export const isMobile = !!navigator.userAgent.match(
  /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
);

let sgToFixed = (num, digit = 2) => {
  //num是数值；digit是保留有效数字位数
  let nums = (num || 0).toString().split(".");
  return nums[0] + "." + (nums[1] || "0").padEnd(digit, "0");
};
export function formatNum(val) {
  if (val && val !== 0 && !isNaN(val)) {
    val = Intl.NumberFormat().format(val);
  } else {
    val = "0";
  }
  return sgToFixed(val);
}

export function getfilesize(size) {
  //把字节转换成正常文件大小
  if (!size) return "";
  var num = 1024.0; //byte
  if (size < num) return size.toFixed(2) + "B";
  if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + "KB"; //kb
  if (size < Math.pow(num, 3)) return (size / Math.pow(num, 2)).toFixed(2) + "MB"; //M
  if (size < Math.pow(num, 4)) return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
  return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
}

export function numToBig(money: any) {
  // 阿拉伯数字转换大写
  //汉字的数字
  var cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  //基本单位
  var cnIntRadice = ["", "拾", "佰", "仟"];
  //对应整数部分扩展单位
  var cnIntUnits = ["", "万", "亿", "兆"];
  //对应小数部分单位
  var cnDecUnits = ["角", "分", "毫", "厘"];
  //整数金额时后面跟的字符
  var cnInteger = "整";
  //整型完以后的单位
  var cnIntLast = "圆";
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = "";
  //分离金额后用的数组，预定义
  var parts;
  if (money == "") {
    return "";
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return "";
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  money = money.toString();
  if (money.indexOf(".") == -1) {
    integerNum = money;
    decimalNum = "";
  } else {
    parts = money.split(".");
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != "") {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != "0") {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == "") {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == "") {
    chineseStr += cnInteger;
  }
  return chineseStr;
}
